<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table @row-dblclick="getClick" :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state === 1">开启</span>
          <span style="color: red" v-else-if="scope.row.state === 0">关闭</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120">
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="total, sizes, prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total"
                     @size-change="handleSizeChange"
                     :page-sizes="[5, 10, 15, 30, 50]"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增修改界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
            <!--
              :key：必须指定为你每条数据中的唯一字段
              :label：用户选择之后在下拉框中展示的值
              :value：用户选中值之后要提交时，使用那个字段提交
            -->
            <el-option
                v-for="item in employee"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <!--
            el-cascader：级联选择器框
            options：级联的数据，指向模型层的options字段
          -->
          <el-cascader
              v-model="editForm.parent"
              :options="deptTree"
              :props="{ checkStrictly: true, value:'id', label:'name' }"
              clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


    <!--抽屉代码-->
    <el-drawer
        title="员工管理"
        :visible.sync="table"
        direction="rtl"
        size="50%">

      <!--工具条-->
      <el-col :span="24" class="toolbar">
        <el-table :data="gridData" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column type="index" width="60">
          </el-table-column>
          <el-table-column prop="username" label="名称" width="100">
          </el-table-column>
          <el-table-column prop="phone" label="电话号码" width="110">
          </el-table-column>
          <el-table-column prop="email" label="QQ邮箱" width="120">
          </el-table-column>
          <el-table-column prop="age" label="年龄" width="100">
          </el-table-column>
          <el-table-column prop="state" label="状态" width="100" sortable>
            <template scope="scope">
              <span style="color: green" v-if="scope.row.state === 1">开启</span>
              <span style="color: red" v-else-if="scope.row.state === 0">关闭</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>
          <!--      <el-table-column prop="manager.username" label="负责人" width="120">-->
          <!--      </el-table-column>-->

          <el-table-column label="操作" width="150">
            <template scope="scope">
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--
          disabled：是否不可点击
            true：不可点击
            false：可点击
        -->
        <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
        <el-pagination
            layout="total, sizes, prev, pager, next"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            @size-change="handleSizeChange"
            :page-sizes="[5, 10, 15, 30, 50]"
            style="float:right;">
        </el-pagination>
      </el-col>
    </el-drawer>


  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {getDepartmenListPage, removeDepartmen, batchRemoveDepartmen, editDepartmen, addDepartmen} from '../../api/api';

export default {
  data() {
    return {
      table: false,
      gridData: [],
      options:[],
      filters: {
        keyword: ''
      },
      title:"",
      departments: [],
      employee: [],
      total: 0,
      pageSize: 5,
      currentPage: 1,
      listLoading: false,
      deptTree:[],
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输入便编号', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      editForm: {
        id:null,
        sn:"",
        name:"",
        state:0,
        manager:{},
        parent:{}
      },


    }
  },
  methods: {
    getClick(row){
      // 根据当前行数据的主键Id，发起请求获取到当前行对应的数据，进行赋值
      this.$http.get("/empl/findEmpl/" + row.id)
          .then(result=>{
            this.gridData = result.data;
            this.table = true;
          })
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getDepartments();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    search() {
      this.currentPage = 1;
      this.getDepartments();
    },
    // 获取员工列表
    getEmployee(){
      // 获取后端数据
      this.$http.get("/empl")
      .then(result=>{
        // 给员工表赋值
        this.employee = result.data;
      })
      .catch(result=>{

      })
    },
    findTree(){
      this.$http.get("/dept/findTree")
      .then(result=>{
        this.deptTree = result.data;
        console.log(result.data)
      })
      .catch(result =>{

      })
    },

    //获取部门列表
    getDepartments() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      // 开启忙等
      this.listLoading = true;
      // 发送请求 这个是后端穿到前端的数据
      this.$http.post("/dept", para)
          .then(result => {
            console.log(result);
            // 获取数据后忙等关闭
            this.listLoading = false;
            // 把值赋给表格获取后端数据返回
            result = result.data;
            // 给总条数赋值
            this.departments = result.rows;
            this.total = result.total;
            // 分页书记显示
          })


      // //NProgress.start();
      // getDepartmenListPage(para).then((res) => {
      // 	this.total = res.data.total;
      // 	this.departmens = res.data.departmens;
      // 	this.listLoading = false;
      // 	//NProgress.done();
      // });
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // 发送axios请求 往后端传入数据 拼接一id 这是拼接的id
        this.$http.delete("/dept/" + row.id)

            // 拼接后获取数据
            .then(result => {
              console.log(result.data)
              // 获取后端的返回值给给一个对象
              result = result.data;
              if (result.success) {
                // 如果成功就调用返回值中的信息
                this.$message({
                  // 这是一个json格式
                  message: result.message,
                  type: 'success'
                });
                // 修改页码为第一页
                this.currentPage = 1;
                // 调用函数刷新
                this.getDepartments();
              } else {
                // 删除失败
                // 删除成功
                this.$message({
                  // 这里是键值对
                  message: result.message,
                  type: 'error'
                });
                this.currentPage = 1;
                this.getDepartments();
              }
            })
            .catch(result => {
              this.listLoading = false
              this.$message({
                message: '系统繁忙请稍后再试',
                type: 'error'
              });
            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      // 修改模态框的标题;
      this.title = "编辑",
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
      if(row.dirPath){
       let arr =  row.dirPath.split("/");
       let parents =[];
       for (let i = 1; i < arr.length - 1; i++){
         parents.push(parseInt(arr[i]))
       }
       this.editForm.parent = parents;
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.title = "新增",
      this.editFormVisible = true;
      this.editForm = {
        id:null,
        sn:"",
        name:"",
        state:0,
        manager:{},
        parent:{}
      };
    },
    //编辑
    editSubmit: function () {
      // 表单的数据验证进入方法
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            // 将表单数拷贝
            let para = Object.assign({}, this.editForm);
            // 回显数据
            if (para.parent){
              para.parent = {"id":para.parent[para.parent.length-1]}
            }
            // 发送请求 将表单封装的数据给到后端
            this.$http.put("/dept",para)
            .then(result=>{
              console.log(result)
              this.editLoading = false;
              // 关闭弹出式的模态框
              this.editFormVisible = false;
              // 从回调函数中获取数据 重新给返回字段
              result = result.data;
              // 4.判断删除是否成功

              if (result.success){
                // 删除成功
                // 1.给出成功提示
                this.$message({
                  message: result.message,
                  type: 'success'
                });
                // 2.修改页码为第一页
                this.currentPage = 1;
                // 3.调用函数刷新列表
                this.getDepartments();
              }else {
                // 删除失败
                // 删除成功
                // 1.给出失败提示
                this.$message({
                  message: result.message,
                  type: 'error'
                });
                // 2.修改页码为第一页
                this.currentPage = 1;
                // 3.调用函数刷新列表
                this.getDepartments();
              }
            })

                .catch(result=>{ // 接口调用失败
                  // 1.关闭忙等框
                  this.listLoading = false;
                  // 2.给出自定义失败提示！
                  this.$message({
                    message: '系统繁忙，请重试！',
                    type: 'error'
                  });
            })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove () {
      var ids = this.sels.map(item => item.id);

      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/dept", ids)
            .then(result => {
             result = result.data;
              // 2.判断删除是否成功
              debugger
              if (result.success) {
                console.log('删除成功')
                // 删除成功
                // 1.给出成功提示
                this.$message({
                  message: result.message,
                  type: 'success'
                });

                // 2.修改页码为第一页
                this.currentPage = 1;
                // 3.调用函数刷新列表
                this.getDepartments();

              } else {
                console.log('删除失败')
                // 删除失败
                // 删除成功
                // 1.给出失败提示
                this.$message({
                  message: result.message,
                  type: 'error'
                });
                // 2.修改页码为第一页
                this.currentPage = 1;
                // 3.调用函数刷新列表
                this.getDepartments();
              }

            })

            .catch(result => { // 接口调用失败
              console.log('2222')
              // 1.关闭忙等框
              this.listLoading = false;
              // 2.给出自定义失败提示！
              this.$message({
                message: '系统繁忙，请重试！',
                type: 'error'
              });
            })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getDepartments();
    this.getEmployee();
    this.findTree();
  }
}

</script>

<style scoped>

</style>